<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/9
 * Time: 16:24
 */

namespace common\business\ifs;


use common\business\CommonHelper;
use common\business\Handler;
use common\consts\CommonResources;
use common\result\ActionResult;
use yii\db\ActiveRecord;
use Yii;
use yii\db\StaleObjectException;
use yii\helpers\Json;

abstract class DbCrud extends Handler implements CrudInterface
{
    /**
     * @param $obj ActiveRecord
     * @return ActionResult
     */
    public function create($obj){
        $action = Yii::t('app', 'Create');
        $modelClass = Yii::t('app', get_class($obj));
        if (!$obj->save()) {
            $dbErrorMsg = Json::encode($obj->getErrors());
            return new ActionResult(false, CommonResources::ACTION_NAME_MODEL_FAIL_WITH_REASON($action, $modelClass, CommonHelper::getPrintName($obj), $dbErrorMsg));
        }
        return new ActionResult(true, CommonResources::ACTION_NAME_MODEL_SUCCESS($action, $modelClass, CommonHelper::getPrintName($obj)));
    }

    /**
     * @param $obj ActiveRecord
     * @return ActionResult
     */
    public function update($obj)
    {
        $action = Yii::t('app', 'Update');
        $modelClass = Yii::t('app', get_class($obj));
        if (!$obj->save()) {
            $dbErrorMsg = Json::encode($obj->getErrors());
            return new ActionResult(false, CommonResources::ACTION_NAME_MODEL_FAIL_WITH_REASON($action, $modelClass, CommonHelper::getPrintName($obj), $dbErrorMsg));
        }
        return new ActionResult(true, CommonResources::ACTION_NAME_MODEL_SUCCESS($action, $modelClass, CommonHelper::getPrintName($obj)));
    }

    /**
     * @param $obj ActiveRecord
     * @return ActionResult
     */
    public function delete($obj)
    {
        $action = Yii::t('app', 'Delete');
        $modelClass = Yii::t('app', get_class($obj));
        try {
            if (!$obj->delete()) {
                $dbErrorMsg = Json::encode($obj->getErrors());
                return new ActionResult(false, CommonResources::ACTION_NAME_MODEL_FAIL_WITH_REASON($action, $modelClass, CommonHelper::getPrintName($obj), $dbErrorMsg));
            }
            return new ActionResult(true, CommonResources::ACTION_NAME_MODEL_SUCCESS($action, $modelClass, CommonHelper::getPrintName($obj)));
        } catch (\Exception $e) {
            $dbErrorMsg = CommonHelper::getExceptionMsg($e);
            $this->addError($action, $dbErrorMsg);
            Yii::error(CommonResources::ACTION_FAIL_MSG('Delete', 'Record', $dbErrorMsg));
            return new ActionResult(false, CommonResources::ACTION_NAME_MODEL_FAIL_WITH_REASON($action, $modelClass, CommonHelper::getPrintName($obj), $dbErrorMsg));
        }
    }

    public abstract function read($id);
}